package com.zhiwang.planet.util

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.zhiwang.planet.App
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty


class AppHelper {


    companion object Helper {
        private const val TAG = "AppHelper"

        private const val INVITATION_TAG = "invitecode"

        lateinit var context: App

        private var inviteCode: String by sharePreference()

        fun init(context: App) {
            Helper.context = context
        }


        private fun sharePreference(): ReadWriteProperty<Helper, String> {
            return object : ReadWriteProperty<Helper, String> {
                override fun getValue(thisRef: Helper, property: KProperty<*>): String {
                    val sharePref = context.getSharedPreferences(BuildConfig.SHARE_FILE_NAME, Context.MODE_PRIVATE)
                    return sharePref.getString("invitecode", "nullcode app is not installed by sharing")
                }

                override fun setValue(thisRef: Helper, property: KProperty<*>, value: String) {
                    val editor =
                            context.getSharedPreferences(BuildConfig.SHARE_FILE_NAME, Context.MODE_PRIVATE)
                                    .edit()
                    editor.putString("invitecode", value).apply()
                }
            }
        }

        fun testEnv(): Boolean {
            val sharePref = context.getSharedPreferences(BuildConfig.SHARE_FILE_NAME, Context.MODE_PRIVATE)
            return sharePref.getBoolean("mmmenv", false)
        }

        @SuppressLint("ApplySharedPref")
        fun switchEnv(): Boolean {
            val sharePref = context.getSharedPreferences(BuildConfig.SHARE_FILE_NAME, Context.MODE_PRIVATE)
            val isTestEnv = testEnv().not()
            sharePref.edit().putBoolean("mmmenv", isTestEnv).commit()
            return isTestEnv
        }

        fun setStatusBar(activity: Activity, useThemestatusBarColor: Boolean, withoutUseStatusBarColor: Boolean) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
                val decorView = activity.getWindow().getDecorView()
                var option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                //如果是浅色状态栏，使用浅色flag，以免状态栏文字为深色

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                }
                activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                decorView.setSystemUiVisibility(option)
                if (useThemestatusBarColor) {
                    activity.getWindow().setStatusBarColor(ContextCompat.getColor(activity, R.color.colorPrimary))
                } else {
                    activity.getWindow().setStatusBarColor(Color.TRANSPARENT)
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
                val localLayoutParams = activity.getWindow().getAttributes()
                localLayoutParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or localLayoutParams.flags
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !withoutUseStatusBarColor) {
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
            }
        }

        fun setStatusBarEx(activity: Activity, useThemestatusBarColor: Boolean, withoutUseStatusBarColor: Boolean) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
                val decorView = activity.window.decorView
                val option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                decorView.systemUiVisibility = option
                if (useThemestatusBarColor) {
                    activity.window.statusBarColor = activity.resources.getColor(R.color.white)
                } else {
                    activity.window.statusBarColor = Color.TRANSPARENT
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
                val localLayoutParams = activity.window.attributes
                localLayoutParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or localLayoutParams.flags
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !withoutUseStatusBarColor) {
                activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        }

        @SuppressLint("HardwareIds")
        fun getDeviceIdWithoutGuarantee(context: Context): String {
            if (TextUtils.isEmpty(TokenManager.getDeviceId()).not())
                return TokenManager.getDeviceId()

            val telecomManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
                return "权限不足，无法获取设备号，请在应用管理中授予权限"

            val deviceId: String? = when {
                TextUtils.isEmpty(telecomManager.deviceId).not() -> telecomManager.deviceId
                Build.VERSION.SDK_INT > Build.VERSION_CODES.P -> Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> telecomManager.getImei(0)
                else -> "cannot get deviceid"
            }
            TokenManager.saveDevice(deviceId
                    ?: "无法获取到设备号${if (Build.VERSION.SDK_INT >= 29) "Android 10" else ""}")
            return deviceId ?: "无法获取设备号${if (Build.VERSION.SDK_INT >= 29) "Android 10" else ""}"
        }

        fun isDev(): Boolean {
            return BuildConfig.BUILD_TYPE == "developer" ||BuildConfig.BUILD_TYPE == "测试"
        }


        fun isTest():Boolean{
          return  BuildConfig.BUILD_TYPE == "测试"
        }


    }


}